package com.gitee.feizns.webtemplate.commons.upload.service;

import com.gitee.feizns.webtemplate.commons.upload.UploadEvent;
import com.gitee.feizns.webtemplate.commons.upload.UploadProperties;
import com.gitee.feizns.webtemplate.commons.utils.StreamUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class UploadServiceImpl implements UploadService {

    /**
     * 处理器列表
     */
    private final List<MediaHandler> handles = new ArrayList<>();

    /**
     * 注册处理器
     */
    public final void registeredProcessor(MediaHandler handler) {
        handles.add(handler);
    }

    private UploadProperties uploadProperties;

    public UploadServiceImpl(UploadProperties uploadProperties) {
        this.uploadProperties = uploadProperties;
    }

    @Override
    public void async(UploadEvent event) {
        handle(event);
    }

    @Override
    public void sync(UploadEvent event) {
        handle(event);
    }

    private void handle(UploadEvent event) {
        InputStream[] streams = StreamUtils.copyStream(event.getInputStream(), handles.size());
        for (int i = 0; i < streams.length; i++) {
            handles.get(i).handle(UploadEvent.reset(event, streams[i]), uploadProperties);
        }
    }

}
